<?php

namespace app\admin\model\shop\goods;

use ba\Exception;
use think\Model;
use think\model\concern\SoftDelete;

/**
 * Classify
 */
class Classify extends Model
{
    use SoftDelete;

    protected $defaultSoftDelete = 0;

    // 表名
    protected $name = 'shop_goods_classify';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    /**
     * @throws Exception
     */
    public static function onBeforeUpdate(Model $model): Model
    {
        $classify = self::where('id', $model->getData('id'))->findOrEmpty();
        $pid      = $classify->pid;
        if ($pid != 0 && $pid != $model->getData('pid')) {
            $classifyId = $pid . '-' . $classify->id;
            $count      = (new Goods())->whereFindInSet('classify_id', $classifyId)->count();
            if ($count > 0) {
                throw new Exception('该分类已被绑定，请先解绑后再修改');
            }
        }

        return $model;
    }

    /**
     * 添加后
     * @param $model
     * @return void
     */
    protected static function onAfterInsert($model): void
    {
        if ($model->weigh == 0) {
            $pk = $model->getPk();
            if (strlen($model[$pk]) >= 19) {
                $model->where($pk, $model[$pk])->update(['weigh' => $model->count()]);
            } else {
                $model->where($pk, $model[$pk])->update(['weigh' => $model[$pk]]);
            }
        }
    }

    /**
     * 删除前
     * @param Model $model
     * @return Model
     * @throws Exception
     */
    public static function onBeforeDelete(Model $model): Model
    {
        $child = (new self())->where('pid', $model->id)->findOrEmpty();
        if (!$child->isEmpty()) {
            throw new Exception('该分类下存在子级分类，无法删除');
        }
        $goods = (new Goods())->where('classify_id', 'like', "%$model->id%")->findOrEmpty();
        if (!$goods->isEmpty()) {
            throw new Exception('该分类已被绑定，无法删除');
        }

        return $model;
    }
}